package com.howard.base.interceptor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * 文件过大时的异常处理拦截器
 *
 * @author 程进之
 * @since JDK1.6
 * @history 2012-10-15 程进之 新建
 */
public class FileTooLargeListener implements PreResultListener {

    /** 文件过大跳转Result */
    public final static String TOO_LARGE_RESULT = "file_too_large";

    @Override
    public void beforeResult(ActionInvocation invocation, String resultCode) {
        if (!Action.INPUT.equals(resultCode)) {
            return;
        }
        Object action = invocation.getAction();
        ValidationAware validation = null;
        if (action instanceof ValidationAware) {
            validation = (ValidationAware) action;
        }
        if (validation != null) {
            Collection<String> actionErrors = validation.getActionErrors();
            for (Iterator<String> iterator = actionErrors.iterator(); iterator.hasNext();) {
                String actionError = iterator.next();
                if (actionError.startsWith("the request was rejected because its size")) {
                    Matcher m = Pattern.compile("\\d+").matcher(actionError);
                    String s1 = "";
                    if (m.find()) {
                        s1 = m.group();
                    }
                    String s2 = "";

                    if (m.find()) {
                        s2 = m.group();
                    }
                    List<String> lstActionErrors = new ArrayList<String>();
                    lstActionErrors.add("你上传的文件大小（" + s1 + "）超过允许的最大值（" + s2 + "）");
                    lstActionErrors.add("服务器拒绝了本次请求!");
                    validation.setActionErrors(lstActionErrors);
                    invocation.setResultCode(TOO_LARGE_RESULT);
                    return;
                }
            }
        }
    }
}
